package at.fhhgb.mc.android.mfb_hgb.activity;

import java.util.ArrayList;

import org.apache.http.message.BasicNameValuePair;

import android.app.ActionBar;
import android.app.Fragment;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import at.fhhgb.mc.android.mfb_hgb.R;
import at.fhhgb.mc.android.mfb_hgb.activity.dialog.ProgressDialog;
import at.fhhgb.mc.android.mfb_hgb.dal.SelectUser;
import at.fhhgb.mc.android.mfb_hgb.dal.UpdateUser;
import at.fhhgb.mc.android.mfb_hgb.model.TaskCaller;
import at.fhhgb.mc.android.mfb_hgb.model.User;

public class FragmentProfile extends Fragment implements TaskCaller, TextWatcher {
	private static final String LOG_TAG = "FragmentProfile";
	private User curUser;
	private boolean isWatcherAdded = false;
	private boolean isTextChanged = false;
	// private InputMethodManager lManager;
	private ProgressDialog pDialog;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.fragment_profile, null);

		// request current user data
		new SelectUser(this).execute(new BasicNameValuePair("Username", getActivity().getSharedPreferences(getString(R.string.preferences_key), getActivity().MODE_PRIVATE).getString("username", null)));

		// set focus & keyboard
		// final EditText e = (EditText)
		// view.findViewById(R.id.pro_edit_first_name);

		// lManager = (InputMethodManager)
		// getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
		//
		// e.post(new Runnable() {
		// public void run() {
		// e.requestFocus();
		// lManager.showSoftInput(e, 0);
		// }
		// });

		pDialog = new ProgressDialog(getActivity());
		pDialog.show();

		return view;
	}

	@SuppressWarnings("unchecked")
	@Override
	public void onBackgroundTaskCompleted(Object result) {
		if (getActivity() != null) {

			if (result.getClass() != Integer.class) {
				curUser = ((ArrayList<User>) result).get(0);

				// Load Data and add Watchers!
				loadData();
				if (!isWatcherAdded) {
					addWatchers();
				}
			} else {
				curUser = null;
				new SelectUser(this).execute(new BasicNameValuePair("Username", getActivity().getSharedPreferences(getString(R.string.preferences_key), getActivity().MODE_PRIVATE).getString("username", null)));
				Toast.makeText(getActivity(), getText(R.string.saved), Toast.LENGTH_LONG).show();
			}

		} else {
			Log.e(LOG_TAG, "getActivity() is null!");
		}

		pDialog.dismiss();
	}

	private void addWatchers() {
		((EditText) getActivity().findViewById(R.id.pro_edit_first_name)).addTextChangedListener(this);
		((EditText) getActivity().findViewById(R.id.pro_edit_last_name)).addTextChangedListener(this);
		((EditText) getActivity().findViewById(R.id.pro_edit_email)).addTextChangedListener(this);
		((EditText) getActivity().findViewById(R.id.pro_edit_password)).addTextChangedListener(this);
		isWatcherAdded = true;
	}

	public boolean loadData() {
		if (curUser != null) {
			((TextView) getActivity().findViewById(R.id.pro_id)).setText(curUser.getUsername());
			((EditText) getActivity().findViewById(R.id.pro_edit_first_name)).setText(curUser.getFirstname());
			((EditText) getActivity().findViewById(R.id.pro_edit_last_name)).setText(curUser.getLastname());
			((EditText) getActivity().findViewById(R.id.pro_edit_email)).setText(curUser.getEmail());
			((EditText) getActivity().findViewById(R.id.pro_edit_password)).setText(curUser.getPassword());

			isTextChanged = false;
			return true;
		} else {
			return false;
		}
	}

	public void saveData() {
		if (curUser != null && isTextChanged) {
			pDialog.show();
			new UpdateUser(this).execute(new BasicNameValuePair("UserID", String.valueOf(curUser.getUserID())), new BasicNameValuePair("Username", ((TextView) getActivity().findViewById(R.id.pro_id)).getText().toString()), new BasicNameValuePair("Password", ((EditText) getActivity().findViewById(R.id.pro_edit_password)).getText().toString()),
					new BasicNameValuePair("Firstname", ((EditText) getActivity().findViewById(R.id.pro_edit_first_name)).getText().toString()), new BasicNameValuePair("Lastname", ((EditText) getActivity().findViewById(R.id.pro_edit_last_name)).getText().toString()),
					new BasicNameValuePair("Email", ((EditText) getActivity().findViewById(R.id.pro_edit_email)).getText().toString()));

			// update stored password
			SharedPreferences prefs = getActivity().getSharedPreferences(getString(R.string.preferences_key), getActivity().MODE_PRIVATE);
			Editor editor = prefs.edit();
			editor.putString("pwd", ((EditText) getActivity().findViewById(R.id.pro_edit_password)).getText().toString());
			editor.commit();

			Log.d(LOG_TAG, "Send changes to server!");
		}
	}

	@Override
	public void beforeTextChanged(CharSequence s, int start, int count, int after) {
	}

	@Override
	public void onTextChanged(CharSequence s, int start, int before, int count) {
		isTextChanged = true;
		Log.d(LOG_TAG, "Text changed!");
	}

	@Override
	public void afterTextChanged(Editable s) {
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);

		setHasOptionsMenu(true);
	}

	@Override
	public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
		super.onCreateOptionsMenu(menu, inflater);

		inflater.inflate(R.menu.profile, menu);

		ActionBar actionBar = getActivity().getActionBar();

		actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
		actionBar.setDisplayShowTitleEnabled(true);
		actionBar.setTitle(getResources().getStringArray(R.array.nav_items)[2]);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.pro_revert:
			FragmentProfile g = (FragmentProfile) getFragmentManager().findFragmentById(R.id.container);
			g.loadData();
			return true;

		case R.id.pro_accept:
			FragmentProfile h = (FragmentProfile) getFragmentManager().findFragmentById(R.id.container);
			h.saveData();
			return true;
		}

		return super.onOptionsItemSelected(item);
	}
}
